package com.hbnu.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * @author chendikai
 * @date 2024-11-06 上午 10:39
 */
public class DBUtils {

    private static DataSource dataSource;  // 声明数据库连接池对象

    static {
        // 通过反射，以流的方式获取配置文件内容
        InputStream resourceAsStream = DBUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
        Properties properties = new Properties();

        try {
            properties.load(resourceAsStream);   // 加载配置文件

            dataSource = DruidDataSourceFactory.createDataSource(properties);  // 创建数据库连接池对象
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    public static void close(ResultSet resultSet, Statement statement, Connection connection) {
        try {
            if (resultSet != null) {
                resultSet.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        try {
            if (statement != null) {
                statement.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        try {
            if (connection != null) {
                connection.close();  // 归还连接
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
